package com.manager.web.system;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.manager.base.BaseAction;
import com.manager.pojo.system.SysUser;
import com.manager.util.CONSTANT;
import com.manager.util.DateUtil;
import com.manager.util.Log;
import com.manager.util.security.Digest;
import com.opensymphony.xwork2.Action;

public class SysUserAction extends BaseAction {
	private SysUser sysUser;
	
	/*
	 * 添加左边栏菜单
	 */
	public String addUser(){
		int loginUserId = super.getLoginUserId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//查询用户名是否已存在
			int total = super.baseService.queryInt("select count(1) from sys_user where name = ?", sysUser.getName());
			if(total == 1){
				p.print("{\"flag\":false,\"msg\":\"该用户名已存在\"}");
			}else{
				//保存基本用户信息
				SysUser su = new SysUser();
				su.setName(sysUser.getName());
				su.setPassword(sysUser.getPassword());
				su.setEmail(sysUser.getEmail());
				su.setDepartmentId(sysUser.getDepartmentId());
				su.setCreateById(loginUserId);
				su.setCreateDateTime(DateUtil.getCurrentDateTime(true));
				su.setUpdateById(loginUserId);
				su.setUpdateDateTime(DateUtil.getCurrentDateTime(true));
				super.baseService.save(su);
				
				//添加该用户相应的角色
				String role = request.getParameter("roles");
				if(role != null && !role.equals("")){
					String[] roles = role.split(",");
					String sql = "INSERT INTO sys_user_role (user_id, role_id, create_by_id, create_date_time, update_by_id, update_date_time) VALUES (?,?,?,?,?,?)";
					
					Object[][] params = new Object[roles.length][6];
					for(int i = 0; i < roles.length; i++){
						params[i][0] = su.getId();
						params[i][1] = Integer.parseInt(roles[i]);
						params[i][2] = loginUserId;
						params[i][3] = DateUtil.getCurrentDateTime(true);
						params[i][4] = loginUserId;
						params[i][5] = DateUtil.getCurrentDateTime(true);
					}
					super.baseService.executeBatch(sql, params);
				}
				
				p.print("{\"flag\":true}");
			}
		}catch(Exception e){
			e.printStackTrace();
			p.print("{\"flag\":false}");
		}finally{
			p.flush();
			p.close();
		}
		return Action.NONE;
	}
	
	/*
	 * 删除左边菜单
	 */
	public String deleteUser(){
		int sysUserId = sysUser.getId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//永远不允许删除"临时用户"
			if(sysUserId == 2){
				p.write("{\"flag\":false,\"msg\":\"永远不允许删除--临时用户\"}");
			}else{
				super.baseService.delete("delete from sys_user where id = ?", sysUser.getId());
				super.baseService.delete("delete from sys_user_role where user_id = ?", sysUser.getId());
				p.write("{\"flag\":true}");
			}
		}catch(Exception e){
			p.write("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		return Action.NONE;
	}
	
	/*
	 * 由id查询user
	 */
	public String queryUserById(){
		String hql = "FROM SysUser m WHERE m.id = ?";
		sysUser = (SysUser)super.baseService.getObject(SysUser.class, sysUser.getId());
		
		String rs = super.baseService.queryString("select cast(group_concat(role_id) as char) roles from sys_user_role where user_id = ?", sysUser.getId());
		
		request.setAttribute("roles", rs);
		super.forward("system/userUpdate.jsp");
		return Action.NONE;
	}
	
	/*
	 * 更新user
	 */
	public String updateUser(){
		PrintWriter p = null;
		int loginUserId = super.getLoginUserId();
		
		try{
			p = response.getWriter();
			
			//查询除该id用户名，其它所有用户名中该用户名是否存在
			int total = super.baseService.queryInt("select count(1) from sys_role where name = ? and id != ?", sysUser.getName(), sysUser.getId());
			if(total == 1){
				p.print("{\"flag\":false,\"msg\":\"该用户名已存在\"}");
			}else{
				//更新基本用户信息
				SysUser su = super.baseService.getObject(SysUser.class, sysUser.getId());
				su.setName(sysUser.getName());
				su.setEmail(sysUser.getEmail());
				su.setDepartmentId(sysUser.getDepartmentId());
				su.setUpdateById(loginUserId);
				su.setUpdateDateTime(DateUtil.getCurrentDateTime(true));
				super.baseService.save(su);
				
				//删除原有的角色
				super.baseService.delete("delete from sys_user_role where user_id = ?", sysUser.getId());
				
				//添加新的角色
				String role = request.getParameter("roles");
				if(role != null && !role.equals("")){
					String[] roles = role.split(",");
					String sql = "INSERT INTO sys_user_role (user_id, role_id, create_by_id, create_date_time, update_by_id, update_date_time) VALUES (?,?,?,?,?,?)";
					
					Object[][] params = new Object[roles.length][6];
					for(int i = 0; i < roles.length; i++){
						params[i][0] = sysUser.getId();
						params[i][1] = Integer.parseInt(roles[i]);
						params[i][2] = loginUserId;
						params[i][3] = DateUtil.getCurrentDateTime(true);
						params[i][4] = loginUserId;
						params[i][5] = DateUtil.getCurrentDateTime(true);
					}
					super.baseService.executeBatch(sql, params);
				}
				
				p.print("{\"flag\":true}");
			}
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 重置密码
	 */
	public String resetPassword(){
		PrintWriter p = null;
		try{
			p = response.getWriter();
			
			String passwordMD5 = Digest.getMD5(CONSTANT.RESET_PASSWORD);
			super.baseService.update("update sys_user set password = ? where id = ?", passwordMD5, sysUser.getId());
			
			p.write("{\"flag\":true}");
		}catch(Exception e){
			p.write("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		return Action.NONE;
	}
	
	/*
	 * 更新密码
	 */
	public String updateUserPassword(){
		PrintWriter p = null;
		try{
			p = response.getWriter();
			
			super.baseService.update("update sys_user set password = ? where id = ?", sysUser.getPassword(), super.getLoginUserId());
			
			p.write("{\"flag\":true}");
		}catch(Exception e){
			p.write("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		return Action.NONE;
	}
	
	/*
	 * 根据pid查询user，展示树形菜单时用
	 */
	public String queryUserByPid(){
		String root = request.getParameter("jqueryFiletreeId");
		PrintWriter p = null;
		int id = -1;
		StringBuffer sb = new StringBuffer();
		
		try{
			p = response.getWriter();
			
			if(root == null || root.equals("null")){
				return Action.NONE;
			}else if(root.equals("source")){
				id = this.baseService.queryInt("SELECT pid FROM sys_user WHERE id = (SELECT MIN(id) FROM sys_user)");
			}else{
				id = Integer.parseInt(root);
			}
			
			List list = this.baseService.callProList("PRO_QUERYMENUBYPID", id);
			
			if(list.size() > 0){
				sb.delete(0, sb.length());
				
				sb.append("<ul class=\"jqueryFileTree\" style=\"display: none;\">");
				for(int i = 0; i < list.size(); i++){
					Map m = (Map)list.get(i);
					
					if(m.get("leaf").toString().equals("0")){
						sb.append("<li class=\"directory collapsed\">");
							sb.append("<input type=\"checkbox\" style=\"display:none;\" value=\"" + m.get("id").toString() + "\"/>");
							sb.append("<a href=\"#\" rel=\"" + m.get("id").toString() + "\">" + m.get("name").toString() + "</a>");
						sb.append("</li>");
					}else{
						sb.append("<li class=\"file ext_code leaf\">");
							sb.append("<input type=\"checkbox\" style=\"display:none;\" value=\"" + m.get("id").toString() + "\"/>");
							sb.append("<a href=\"" + m.get("url").toString() + "\" target=\"mainRight\">" + m.get("name").toString() + "</a>");
						sb.append("</li>");
					}
					
				}
				sb.append("</ul>");
				
				p.print(sb.toString());
			}else{
				
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * getter and setter
	 */
	public SysUser getSysUser() {
		return sysUser;
	}
	
	public void setSysUser(SysUser sysUser) {
		this.sysUser = sysUser;
	}
}
